﻿using DB2WORD.Logics;
using DB2WORD.Models;
using Newtonsoft.Json;
using System.Windows.Forms;

namespace DB2WORD
{
    public partial class MainForm : Form
    {
        public static MainForm Self { get; private set; }
        public static Project Project { get; private set; }
        public static List<GroupInfo> Groups { get; private set; }
        private Form currentForm;
        private readonly FrmList frmList;
        private readonly FrmDetail frmDetail;
        private readonly FrmEdit frmEdit;
        private readonly FrmMore frmMore;
        private const string AppName = "数据字典编辑助手 - lpz V1.2";
        public MainForm()
        {
            InitializeComponent();
            this.lblMessage.Text = "准备就绪";
            this.pnlBottom.Visible = false;
            this.SetDoubleBuffer();
            Self = this;
            this.frmList = new FrmList();
            this.frmDetail = new FrmDetail();
            this.frmEdit = new FrmEdit();
            this.frmMore = new FrmMore();

            this.Load += async (_, _) => this.Back();
            this.btnBack.Click += async (_, _) => this.Back();
        }

        protected override CreateParams CreateParams
        {
            get
            {
                CreateParams cp = base.CreateParams;
                cp.ExStyle |= 0x02000000;
                return cp;
            }
        }

        private void Shift(Form frm, Action action)
        {
            Action acc = () =>
            {
                frm.FormBorderStyle = FormBorderStyle.None;
                frm.Dock = DockStyle.Fill;
                frm.TopLevel = false;
                Show(frm);
                this.pnlBottom.Visible = !this.frmList.Visible;
                Application.DoEvents();
                action?.Invoke();
                Application.DoEvents();
                frm.Activate();
                frm.Select();
            };
            if(this.InvokeRequired)
            {
                this.Invoke(acc);
            }
            else
            {
                acc();
            }
        }

        internal void Back()
        {
            if(currentForm == frmMore)
            {
                this.Edit(MainForm.Project, MainForm.Groups);
                return;
            }
            if(MainForm.Project != null)
            {
                if(MainForm.Project.IsModified || MainForm.Project.IsDetailsModified)
                {
                    var da = MessageBox.Show("项目发生变化，是否保存？", "提示", MessageBoxButtons.YesNo);
                    if(da == DialogResult.Yes)
                    {
                        this.Save();
                    }
                }
                MainForm.Project.IsModified = false;
                MainForm.Project.IsDetailsModified = false;
            }
            MainForm.Project = null;
            MainForm.Groups = null;
            this.frmList.Text = AppName;
            this.Shift(this.frmList, null);
        }

        private void Show(Form frm)
        {
            if(!this.pnlMain.Controls.Contains(frm))
            {
                this.pnlMain.Controls.Add(frm);
            }
            if(currentForm == frm)
            {
                frm.Visible = true;
                return;
            }
            foreach(Control ctl in this.pnlMain.Controls)
            {
                ctl.Visible = false;
                if(ctl == frm)
                {
                    frm.Visible = true;
                    currentForm = frm;
                }
            }
        }

        internal void Save()
        {
            this.frmList.Save();
            this.RefreshProjectInfo();
            this.SetMessage("保存成功");
        }

        internal void Detail(Project project)
        {
            MainForm.Project = project;
            MainForm.Groups = null;
            this.Text = $"更新 {MainForm.Project.Name} - {AppName}";
            this.RefreshProjectInfo();
            this.Shift(this.frmDetail, () =>
            {
                this.frmDetail.ShowFrom();
            });
        }

        internal void Edit(Project project, List<GroupInfo> tables = null)
        {
            MainForm.Project = project;
            this.RefreshProjectInfo();
            if(tables == null)
            {
                try
                {
                    var jsonFileName = $"{MainForm.Project.Name}.json";
                    if(File.Exists(jsonFileName))
                    {
                        var jsonText = File.ReadAllText(jsonFileName);
                        MainForm.Groups = JsonConvert.DeserializeObject<List<GroupInfo>>(jsonText);
                    }
                }
                catch(Exception ex)
                {
                    var da = MessageBox.Show(this, "出现错误，是否从数据库更新？错误信息：\r\n" + ex.Message, "提示", MessageBoxButtons.YesNo);
                    if(da == DialogResult.Yes)
                    {
                        MainForm.Self.Detail(MainForm.Project);
                    }
                    else
                    {
                        MainForm.Self.Back();
                    }
                    return;
                }
            }
            else
            {
                MainForm.Groups = tables;
            }
            if(MainForm.Groups == null || MainForm.Groups.Count == 0)
            {
                var da = MessageBox.Show(this, "没有表名称列表，是否从数据库更新？", "提示", MessageBoxButtons.YesNo);
                if(da == DialogResult.Yes)
                {
                    MainForm.Self.Detail(MainForm.Project);
                }
                else
                {
                    MainForm.Self.Back();
                }
            }
            else
            {
                this.Text = $"维护 {MainForm.Project.Name} - {AppName}";
                this.Shift(this.frmEdit, () =>
                {
                    this.frmEdit.ShowFrom();
                });
            }
        }

        internal void More()
        {
            this.Text = $"分析 {MainForm.Project.Name} - {AppName}";
            this.Shift(this.frmMore, () =>
            {
                this.frmMore.ShowFrom();
            });
        }

        internal void SetMessage(string message)
        {
            this.lblMessage.Text = message.Replace(Environment.NewLine, "->");
            Application.DoEvents();
        }

        internal void RefreshProjectInfo()
        {
            if(MainForm.Project != null)
            {
                this.lblVersion.Text = $"版本号：{Project.Version}";
                this.lblCreateTime.Text = $"创建时间：{Project.CreateTime:yyyy-MM-dd HH:mm:ss}";
                this.lblUpdateTime.Text = $"更新时间：{(Project.LastUpdateTime ?? Project.CreateTime):yyyy-MM-dd HH:mm:ss}";
            }
        }
    }
}
